//
//  LoginViewController.m
//  Cat
//
//  Created by lushitong on 2018/11/29.
//  Copyright © 2018年 lushitong. All rights reserved.
//

#import "LoginViewController.h"
#import "FLProgressHUD.h"
#import "HttpUserManager.h"
#import "WebViewController.h"
#import "HttpWebManager.h"
#import "InviteCodeViewController.h"

@interface LoginViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UITextField *phoneTextFiled;
@property (nonatomic, strong) UIView *phoneBottomView;
@property (nonatomic, strong) UITextField *verCodeTextFiled;
@property (nonatomic, strong) UIButton *sendVerButton;
@property (nonatomic, strong) UIView *verCodeBottomView;

@property (nonatomic, strong) UIButton *selectButton;
@property (nonatomic, strong) UILabel *userInfoLabel;

@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UILabel *infoLabel;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	[self loadAllSubViews];
	self.topTitleView.backgroundColor = [UIColor clearColor];
	[self.topTitleView setDetailDic:@{Nav_LeftTxt:@"返回",Nav_Title:@"登录"}.mutableCopy];
	self.topTitleView.baseTitleLbl.font = [UIFont boldSystemFontOfSize:kQKFitFont(16)];
	self.topTitleView.baseTitleLbl.textColor = COLOR_WITH_HEX(0x4C4947);
	self.topTitleView.bottomLineView.hidden = YES;
	
	[self.view bringSubviewToFront:self.topTitleView];
	[self.phoneTextFiled becomeFirstResponder];
}

- (void)loadAllSubViews {
	[self.view addSubview:self.backImageView];
	[self.backImageView addSubviews:@[self.phoneTextFiled,
									  self.phoneBottomView,
									  self.verCodeTextFiled,
									  self.verCodeBottomView,
									  self.sendVerButton,
									  self.loginButton,
									  self.infoLabel,
									  self.selectButton,
									  self.userInfoLabel]];
	
	[self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.edges.equalTo(self.view);
	}];
	
	[self.phoneTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.equalTo(self.backImageView.mas_left).offset(kQKFitModuleDecimal(28));
		make.top.equalTo(self.backImageView.mas_top).offset(kQKFitModuleDecimal(111));
		make.right.equalTo(self.backImageView.mas_right).offset(-kQKFitModuleDecimal(28));
		make.height.equalTo(@(30));
	}];
	
	[self.phoneBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.and.right.equalTo(self.phoneTextFiled);
		make.top.equalTo(self.phoneTextFiled.mas_bottom);
		make.height.equalTo(@(kQKFitModuleDecimal(1)));
	}];
	
	[self.verCodeTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.and.right.equalTo(self.phoneTextFiled);
		make.top.equalTo(self.phoneBottomView.mas_bottom).offset(kQKFitModuleDecimal(35));
		make.height.equalTo(@(30));
	}];
	
	[self.verCodeBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.and.right.equalTo(self.phoneBottomView);
		make.top.equalTo(self.verCodeTextFiled.mas_bottom);
		make.height.equalTo(@(kQKFitModuleDecimal(1)));
	}];
	
	[self.sendVerButton mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.equalTo(CGSizeMake(kQKFitModuleDecimal(66), 28));
		make.right.equalTo(self.verCodeBottomView.mas_right);
		make.bottom.equalTo(self.verCodeBottomView.mas_bottom).offset(-kQKFitModuleDecimal(8));
	}];
	
	[self.selectButton mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.equalTo(CGSizeMake(kQKFitModuleDecimal(20.0), kQKFitModuleDecimal(20.0)));
		make.left.equalTo(self.verCodeBottomView.mas_left);
		make.top.equalTo(self.verCodeBottomView.mas_bottom).offset(10);
	}];
	
	[self.userInfoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.centerY.equalTo(self.selectButton.mas_centerY);
		make.left.equalTo(self.selectButton.mas_right).offset(kQKFitModuleDecimal(10.0));
	}];
	
	[self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.and.right.equalTo(self.verCodeBottomView);
		make.top.equalTo(self.verCodeBottomView.mas_bottom).offset(46);
		make.height.equalTo(@(kQKFitModuleDecimal(40)));
	}];
	
	[self.infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
		make.top.equalTo(self.loginButton.mas_bottom).offset(kQKFitModuleDecimal(19));
		make.centerX.equalTo(self.backImageView.mas_centerX);
		make.height.equalTo(@(kQKFitModuleDecimal(17)));
	}];

	
	[self setPlaceholder:@"请输入手机号" andWith:self.phoneTextFiled];
	[self setPlaceholder:@"4位验证码" andWith:self.verCodeTextFiled];
}

- (void)textFieldValueChanged:(UITextField *)textField {
	if ([textField isEqual:self.phoneTextFiled]) {
		if (textField.text.length > 10) {
			self.loginButton.enabled = YES;
			self.sendVerButton.enabled = YES;
		}
	}
}

- (void)loginActionWithButton:(UIButton *)button {
	if (self.phoneTextFiled.text.length < 11) {
		[FLProgressHUD showSuccess:@"请输入正确手机号"];
		return;
	}
	
	if (self.phoneTextFiled.text.length < 4) {
		[FLProgressHUD showSuccess:@"请输入正确的验证码"];
		return;
	}
	
	if (!self.selectButton.selected) {
		[FLProgressHUD showError:@"请同意用户服务和隐私政策"];
		return;
	}
    
    [HttpUserManager getInviteStausByPhone:self.phoneTextFiled.text success:^(BOOL inviteCode) {
        if (inviteCode) {
            [HttpUserManager loginWithPhoneNumber:self.phoneTextFiled.text andVerifyCode:self.verCodeTextFiled.text inviteCode:@"" withSuccuss:^(NSString * _Nonnull token) {
                UDToken = token;
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(NSInteger code, NSString * _Nonnull message) {
                [FLProgressHUD showError:message];
            }];
        } else {
            /// 没有邀请码  去跳转到选择邀请码
            InviteCodeViewController *inviteVC = [[InviteCodeViewController alloc] init];
            inviteVC.phoneString = self.phoneTextFiled.text;
            inviteVC.verCodeString = self.verCodeTextFiled.text;
            [self.navigationController pushViewController:inviteVC animated:YES];
        }
    } failure:^(NSInteger code, NSString *message) {
        [FLProgressHUD showError:message];
    }];
   
}

- (void)userInfoAction {
	WebViewController *vc = [[WebViewController alloc] init];
	vc.URL = [HttpWebManager getYinSi];
	[self.navigationController pushViewController:vc animated:YES];
}

- (void)openCountdown:(UIButton *)button {
	__block NSInteger time = 59; //倒计时时间
	
	dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
	dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
	
	dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
	
	dispatch_source_set_event_handler(_timer, ^{
		if(time <= 0){ //倒计时结束，关闭
			dispatch_source_cancel(_timer);
			dispatch_async(dispatch_get_main_queue(), ^{
				//设置按钮的样式
				[button setTitle:@"重发验证码" forState:UIControlStateNormal];
				button.selected = YES;
				button.userInteractionEnabled = YES;
			});
			
		}else{
			int seconds = time % 60;
			dispatch_async(dispatch_get_main_queue(), ^{
				//设置按钮显示读秒效果
				[button setTitle:[NSString stringWithFormat:@"%.2ds", seconds] forState:UIControlStateNormal];
				button.selected = NO;
				button.userInteractionEnabled = NO;
			});
			time--;
		}
	});
	dispatch_resume(_timer);
}

- (void)senVerCodeWithButton:(UIButton *)codeButton {
	if (self.phoneTextFiled.text.length < 11) {
		[FLProgressHUD showSuccess:@"请输入正确的手机号"];
		return;
	}
	[HttpUserManager sendVerifyCodeWithMobile:self.phoneTextFiled.text withSuccuss:^(NSDictionary * _Nonnull dict) {
		[self openCountdown:codeButton];
	} failure:^(NSInteger code, NSString * _Nonnull message) {
		[FLProgressHUD showError:message];
	}];
}


- (void)setPlaceholder:(NSString *)placeholder andWith:(UITextField *)textFiled {
	NSDictionary *atts = @{NSForegroundColorAttributeName: COLOR_WITH_HEX(0xCDC7C4),
						   NSFontAttributeName: textFiled.font};
	NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:placeholder attributes:atts];
	textFiled.attributedPlaceholder = attStr;
}

- (void)changSelectAction:(UIButton *)selectButton {
	self.selectButton.selected = !selectButton.selected;
}
#pragma mark----- delegate -----

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	return YES;
}

#pragma mark----- lazy init -----

- (UIImageView *)backImageView {
	if (!_backImageView) {
		_backImageView = [[UIImageView alloc] init];
		_backImageView.backgroundColor = [UIColor whiteColor];
		_backImageView.userInteractionEnabled = YES;
	}
	return _backImageView;
}

- (UITextField *)phoneTextFiled {
	if (!_phoneTextFiled) {
		_phoneTextFiled = [[UITextField alloc] init];
		_phoneTextFiled.font = [UIFont systemFontOfSize:kQKFitModule(16)];
		_phoneTextFiled.textColor = COLOR_WITH_HEX(0x4C4947);
		_phoneTextFiled.tintColor = COLOR_WITH_HEX(0xFFC236);
		_phoneTextFiled.delegate = self;
		[_phoneTextFiled addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
		_phoneTextFiled.keyboardType = UIKeyboardTypeNumberPad;
	}
	return _phoneTextFiled;
}

- (UIView *)phoneBottomView {
	if (!_phoneBottomView) {
		_phoneBottomView = [[UIView alloc] init];
		_phoneBottomView.backgroundColor = COLOR_WITH_HEX(0xCDC7C4);
	}
	return _phoneBottomView;
}

- (UITextField *)verCodeTextFiled {
	if (!_verCodeTextFiled) {
		_verCodeTextFiled = [[UITextField alloc] init];
		_verCodeTextFiled.font = [UIFont systemFontOfSize:kQKFitModule(16)];
		_verCodeTextFiled.textColor = COLOR_WITH_HEX(0x4C4947);
		_verCodeTextFiled.tintColor = COLOR_WITH_HEX(0xFFC236);
		_verCodeTextFiled.delegate = self;
		_verCodeTextFiled.keyboardType = UIKeyboardTypeNumberPad;
		[_verCodeTextFiled addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
	}
	return _verCodeTextFiled;
}

- (UIButton *)sendVerButton {
	if (!_sendVerButton) {
		_sendVerButton = [UIButton buttonWithType:UIButtonTypeCustom];
		UIImage *disImage = [UIImage imageWithColor:COLOR_WITH_HEX(0xCDC7C4)];
		[_sendVerButton setBackgroundImage:[UIImage imageWithColor:COLOR_WITH_HEX(0xCDC7C4)] forState:UIControlStateNormal];
		[_sendVerButton setBackgroundImage:[UIImage imageWithColor:COLOR_WITH_HEX(0x756D68)] forState:UIControlStateSelected];
		[_sendVerButton setBackgroundImage:disImage forState:UIControlStateDisabled];
		[_sendVerButton setTitle:@"验证码" forState:UIControlStateNormal];
		_sendVerButton.titleLabel.font = [UIFont systemFontOfSize:kQKFitFont(12)];
		
		[_sendVerButton setTitleColor:COLOR_WITH_HEX(0x666666) forState:UIControlStateNormal];
		[_sendVerButton setTitleColor:COLOR_WITH_HEX_A(0x000000, 0.8) forState:UIControlStateSelected];
		_sendVerButton.layer.cornerRadius = kQKFitModule(2);
		_sendVerButton.layer.masksToBounds = YES;
		_sendVerButton.selected = NO;
		[_sendVerButton addTarget:self action:@selector(senVerCodeWithButton:) forControlEvents:UIControlEventTouchUpInside];
	}
	return _sendVerButton;
}

- (UIView *)verCodeBottomView {
	if (!_verCodeBottomView) {
		_verCodeBottomView = [[UIView alloc] init];
		_verCodeBottomView.backgroundColor = COLOR_WITH_HEX(0xCDC7C4);
	}
	return _verCodeBottomView;
}

- (UIButton *)loginButton {
	if (!_loginButton) {
		UIImage *nmImage = [UIImage imageWithColor:COLOR_WITH_HEX(0xFFC236)];
		UIImage *hlImage = [nmImage addBlackMask];
		UIImage *disImage = [UIImage imageWithColor:COLOR_WITH_HEX(0xCDC7C4)];
		
		_loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[_loginButton setTitle:@"登录" forState:UIControlStateNormal];
		
		[_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
		[_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
		
		[_loginButton setBackgroundImage:nmImage forState:UIControlStateNormal];
		[_loginButton setBackgroundImage:hlImage forState:UIControlStateSelected];
		[_loginButton setBackgroundImage:disImage forState:UIControlStateDisabled];
		[_loginButton addTarget:self action:@selector(loginActionWithButton:) forControlEvents:UIControlEventTouchUpInside];
		_loginButton.layer.cornerRadius = kQKFitModule(5);
		_loginButton.layer.masksToBounds = YES;
		_loginButton.enabled = NO;
	}
	return _loginButton;
}

- (UILabel *)infoLabel {
	if (!_infoLabel) {
		_infoLabel = [UILabel labelWithText:@"无需注册即可使用手机号直接登录" font:[UIFont systemFontOfSize:kQKFitFont(12)] textColor:COLOR_WITH_HEX(0xCDC7C4)];
		_infoLabel.textAlignment = NSTextAlignmentCenter;
	}
	return _infoLabel;
}

- (UIButton *)selectButton {
	if (!_selectButton) {
		_selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[_selectButton setImage:[UIImage imageNamed:@"not_select"] forState:UIControlStateNormal];
		[_selectButton setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
		[_selectButton addTarget:self action:@selector(changSelectAction:) forControlEvents:UIControlEventTouchUpInside];
		_selectButton.selected = YES;
	}
	return _selectButton;
}

- (UILabel *)userInfoLabel {
	if (!_userInfoLabel) {
		_userInfoLabel = [UILabel labelWithText:@"我已阅读并同意用户服务协议和隐私政策" font:[UIFont systemFontOfSize:kQKFitFont(14)] textColor:COLOR_WITH_HEX(0xCDC7C4)];
		_userInfoLabel.userInteractionEnabled = YES;
		UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userInfoAction)];
		[_userInfoLabel addGestureRecognizer:tapGes];
	}
	return _userInfoLabel;
}

@end
